import { constantRouterMap, asyncRouterMap } from '@/router'
import Layout from '@/views/layout/Layout'
// 递归查询用户权限
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}
// 递归开始检索
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    redirect: '',
    livePlat: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = state.addRouters.concat(routers)
      state.routers = constantRouterMap.concat(routers)
    },
    SET_PLAT: (state, plat) => {
      state.livePlat = plat
    },
    SET_REDIRECT: (state, redirect) => {
      state.redirect = redirect
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        // 接收权限信息，把name和id筛选出备用
        const rolee = data
        var accessedRouters
        var rolee2 = []
        var modify = []
        if (rolee.length !== 0) {
          rolee.map(function(item) {
            /* 修改新版权限 */
            // return item.menuCode
            if (item.powerType === 'menu') {
              const val = item.powerCode.indexOf('-')
              if (val !== -1) {
                const newVal = item.powerCode.substring(val + 1, item.powerCode.length)
                rolee2.push(newVal)
              }
            }
          })
          accessedRouters = filterAsyncRouter(asyncRouterMap, rolee2)
          console.log(rolee2)
          // 此处筛查平台
          var role2 = []
          /*  = asyncRouterMap.map(function(item) {
            return item.meta.roles
          }) */
          asyncRouterMap.forEach(function(item) {
            if (!Array.isArray(item.meta.roles) && item.meta.roles) {
              role2.push(item.meta.roles)
            }
          })
          // 此处有改动！
          role2.push('sunData')
          role2.push('search')
          console.log(role2)
          var tempRole1 = {}
          var tempRole2 = []
          for (var i = 0; i < role2.length; i++) {
            tempRole1[role2[i]] = true
          }
          for (var j = 0; j < rolee2.length; j++) {
            if (!tempRole1[rolee2[j]]) {
              tempRole2.push(rolee2[j])
            }
          }
          var endRoless = []
          for (const l in rolee) {
            for (var k = 0; k < tempRole2.length; k++) {
              // 开始筛查
              if (rolee[l].powerType === 'menu') {
                if (rolee[l].powerCode.includes(tempRole2[k])) {
                  endRoless.push(rolee[l])
                  break
                }
              }
            }
          }
          // console.log(endRoless)
          var endReverse = endRoless.reverse() // 正确顺序
          // 此处添加分组平台，循环加入
          // 逻辑有所改动，平台分二级 2019-11-12
          var middleArr = []
          endReverse.forEach(item => {
            const resultIndex = item.powerName.indexOf('-')
            const resultPlat = item.powerName.substring(0, resultIndex)
            if (middleArr.indexOf(resultPlat) < 0) {
              middleArr.push(resultPlat)
            }
          })
          // console.log(endReverse)
          var objArr = []
          middleArr.forEach(val => {
            var obj = {
              name: val,
              son: [],
              powerCode: null
            }
            for (let i = 0; i < endReverse.length; i++) {
              // 此处必须绝对相同 有坑 待优化 ****
              if (endReverse[i].powerName.indexOf(val) === 0) {
                var arrResult = endReverse[i].powerName.indexOf('-')
                var arrPlats = endReverse[i].powerName.substr(arrResult + 1, endReverse[i].powerName.length)
                var powerCodess = endReverse[i].powerCode.indexOf('-')
                var powerCodezz = endReverse[i].powerCode.indexOf('|')
                var lastPower = endReverse[i].powerCode.substring(powerCodess + 1, powerCodezz)
                if (!obj.powerCode) {
                  obj.powerCode = lastPower
                }
                if (obj.son.length < 3) {
                  obj.son.push(arrPlats)
                }
              }
            }
            objArr.push(obj)
          })
          commit('SET_PLAT', objArr)
          for (let p = 0; p < objArr.length; p++) {
            var dataRouter = {
              alwaysShow: true,
              path: '/platManagers/' + p,
              component: Layout,
              meta: { roles: objArr[p].powerCode, title: objArr[p].name, icon: 'itemPlat' },
              children: []
            }
            var arrSon1 = {
              path: objArr[p].powerCode + 'userManager',
              component: () => import('@/views/liantong/index'), // btnList:endReverse[o].btnList,
              meta: { title: '用户管控', roles: 'allData', platformId: objArr[p].powerCode, powerName: objArr[p].powerCode }
            }
            var arrSon2 = {
              path: objArr[p].powerCode + 'river',
              component: () => import('@/views/liantong/aaariver'), // btnList:endReverse[o].btnList,
              meta: { title: 'AAA业务明细', roles: 'allData', platformId: objArr[p].powerCode, powerName: objArr[p].powerCode }
            }
            var arrSon3 = {
              path: objArr[p].powerCode + 'charts',
              component: () => import('@/views/liantong/chart'), // btnList:endReverse[o].btnList,
              meta: { title: '分平台概要', roles: 'allData', platformId: objArr[p].powerCode, powerName: objArr[p].powerCode }
            }
            if (objArr[p].son.indexOf('概要数据') > -1) {
              dataRouter.children.push(arrSon3)
            }
            if (objArr[p].son.indexOf('AAA业务明细') > -1) {
              dataRouter.children.push(arrSon2)
            }
            if (objArr[p].son.indexOf('用户管控') > -1) {
              dataRouter.children.push(arrSon1)
            }
            accessedRouters.splice(1, 0, dataRouter)
            modify.push(dataRouter)
          }
          /* for (var o = 0; o < endReverse.length; o++) {
            accessedRouters.splice(1, 0, {
              path: '/platManagers/' + o,
              component: Layout,
              meta: { roles: endReverse[o].powerCode, title: endReverse[o].powerName, icon: 'itemPlat' },
              children: [{
                path: endReverse[o].powerCode,
                name: endReverse[o].powerCode,
                component: () => import('@/views/liantong/index'), // btnList:endReverse[o].btnList,
                meta: { title: '用户管控', roles: 'allData', platformId: endReverse[o].powerCode, powerName: endReverse[o].powerCode }
              }, {
                path: endReverse[o].powerCode + 'index',
                name: endReverse[o].powerCode + 'Index',
                component: () => import('@/views/liantong/aaariver'), // btnList:endReverse[o].btnList,
                meta: { title: 'AAA业务流水查询', roles: 'allData', platformId: endReverse[o].powerCode, powerName: endReverse[o].powerCode }
              }]
            })
          } */
        } else {
          accessedRouters = []
        }
        var path = ''
        console.log(rolee2)
        // 首先进入中心概要
        if (rolee2.indexOf('sunData') > -1) {
          path = '/search/allData'
        } else {
          // 没有概要权限，进入欢迎页
          if (rolee2.indexOf('search') > -1) {
            path = '/dashboard'
          } else {
            // 没有中心权限，进入分平台概要
            /* for (let i = 0; i < rolee2.length; i++) {
              console.log(rolee2[i])
              if (rolee2[i].indexOf('sunData') > -1) {
                path = lastPathResult.path + lastPathResult.path
                break
              }
            } */
            for (let z = 0; z < modify.length; z++) {
              for (let f = 0; f < modify[z].children.length; f++) {
                if (modify[z].children.length > 0) {
                  if (modify[z].children[f].path.indexOf('charts') > -1) {
                    path = modify[z].path + '/' + modify[z].children[f].path
                    break
                  }
                }
              }
            }
            // 没有分平台概要，进入欢迎页，吐槽产品经理，二货设计!
            if (path === '') {
              path = '/dashboard'
            }
          }
        }
        console.log(path)
        commit('SET_REDIRECT', path)
        commit('SET_ROUTERS', accessedRouters)
        resolve(accessedRouters)
      })
    }
  }
}
export default permission
